const { pool } = require('../config/db.js')
const bcrypt = require('bcryptjs')
const { getDb } = require('../config/db.js')
const { ObjectId } = require('mongodb')

class User {
  static async findByUsername(username) {
    const [rows] = await pool.query(
      `SELECT id, username, email, password, api_key, theme, model, temperature,
       created_at, updated_at FROM users WHERE username = ?`,
      [username]
    )
    return rows[0]
  }
  static async findByEmail(email) {
    const [rows] = await pool.query(
      `SELECT id, username, email, password, api_key, theme, model, temperature,
       created_at, updated_at FROM users WHERE email = ?`,
      [email]
    )
    return rows[0]
  }

  static async findById(id) {
    const [rows] = await pool.query(
      `SELECT id, username, email, password, api_key, theme, model, temperature,
       created_at, updated_at FROM users WHERE id = ?`,
      [id]
    )
    return rows[0]
  }

  static async create(userData) {
    const { username, password, email } = userData
    const hashedPassword = await bcrypt.hash(password, 10)

    const [result] = await pool.query(
      'INSERT INTO users (username, email, password) VALUES (?, ?, ?)',
      [username, email, hashedPassword]
    )

    return result.insertId
  }

  static async updateSettings(userId, settings) {
    const { theme, api_key, model, temperature } = settings
    const [result] = await pool.query(
      'UPDATE users SET theme = ?, api_key = ?, model = ?, temperature = ? WHERE id = ?',
      [theme, api_key, model, temperature, userId]
    )
    return result.affectedRows > 0
  }

  static async comparePassword(password, hashedPassword) {
    if (!password || !hashedPassword) {
      console.error('比较密码失败：', {
        passwordProvided: !!password,
        hashedPasswordExists: !!hashedPassword
      });
      throw new Error('密码或哈希密码不能为空');
    }
    return await bcrypt.compare(password, hashedPassword)
  }

  static async updateEmail(userId, newEmail) {
    const [result] = await pool.query(
      'UPDATE users SET email = ? WHERE id = ?',
      [newEmail, userId]
    );
    return result.affectedRows > 0;
  }

  static async updatePassword(userId, newPassword) {
    const hashedPassword = await bcrypt.hash(newPassword, 10);

    const [result] = await pool.query(
      'UPDATE users SET password = ? WHERE id = ?',
      [hashedPassword, userId]
    );

    if (result.affectedRows === 0) {
      throw new Error('更新密码失败');
    }

    return true;
  }

}

module.exports = User
